/* 
 * File:   ShortMsgItemDao.hpp
 * Author: bd
 *
 * Created on March 28, 2011, 7:50 PM
 */

#ifndef SHORTMSGITEMDAO_HPP
#define	SHORTMSGITEMDAO_HPP
#include "Dao.hpp"
#include <vector>
#include <soci/soci.h>
#include "ShortMsgItem.hpp"

class ShortMsgItemDao : public Dao {
public:
    ShortMsgItemDao(Database& session);
    virtual ~ShortMsgItemDao();

    void getItems(std::vector<ShortMsgItem>& items, int n, int groupId);
    void updateItem(const ShortMsgItem& item);
    void loadTestData(int n, int groupId);

protected:
    int getMaxXid(int groupId);
    int updateItemsToSelect(int groupId, int n, int &maxXid);
private:
    ShortMsgItemDao(const ShortMsgItemDao&);
    ShortMsgItemDao & operator=(const ShortMsgItemDao&);

};


namespace soci {

    template<> struct type_conversion<ShortMsgItem> {
        typedef values base_type;

        static void from_base(values const & v, indicator /* ind */, ShortMsgItem & p) {
            std::tm t;
            
            p.id = v.get<int>("id");

            p.groupId = v.get<int>("group_id");

            p.xid = v.get<int>("xid");
            p.toAddr = v.get<std::string>("to_addr", "");
            p.fromAddr = v.get<std::string>("from_addr", "");

            memset(&t, 0, sizeof(std::tm));
            t = v.get<std::tm>("insert_date");
            p.insertDate = boost::posix_time::ptime_from_tm (t);

            memset(&t, 0, sizeof(std::tm));
            t = v.get<std::tm>("last_update");
            p.lastUpdate = boost::posix_time::ptime_from_tm (t);
            p.status = static_cast<ShortMsgItem::Status>(v.get<int>("status", ShortMsgItem::INITIAL));
            p.handler = v.get<std::string>("handler", "");
            p.retry = v.get<int>("retry");
            // p.gender will be set to the default value "unknown"
            // when the column is null:
            //p.gender = v.get<std::string>("GENDER", "unknown");

        }

        static void to_base(const ShortMsgItem & p, values & v, indicator & ind) {
            v.set("id", p.id);
            v.set("group_id", p.groupId);
            v.set("xid", p.xid);
            v.set("to_addr", p.toAddr);
            v.set("from_addr", p.fromAddr);
            v.set("insert_date", boost::posix_time::to_tm(p.insertDate));
            v.set("last_update", boost::posix_time::to_tm(p.lastUpdate));
            v.set("status", static_cast<int>(p.status));
            v.set("handler", p.handler);
            v.set("retry", p.retry);
            ind = i_ok;
        }
    };
}
#endif	/* SHORTMSGITEMDAO_HPP */